//
//  ViewController.m
//  UIWebviewWithCookie
//
//  Created by hudong on 16/7/9.
//  Copyright © 2016年 ZPengs. All rights reserved.
//

#import "ViewController.h"
#import "NJKWebViewProgressView.h"
#import "NJKWebViewProgress.h"
#import "detailViewController.h"

//#define YourURL @"https://www.lialoan.com/Driver/my_center.html"
@interface ViewController ()<UIWebViewDelegate,NJKWebViewProgressDelegate>
{
    NJKWebViewProgressView *_webViewProgressView;
    NJKWebViewProgress *_webViewProgress;
     BOOL loadSuccess;
//    UIView *tempView;
}
@property (nonatomic,strong)UIWebView *webView;
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
   
    NSInteger stateBatHeight =20;
   
    self.webView.scrollView.frame =self.webView.frame;
    _webView.backgroundColor = [UIColor whiteColor];
    _webView.scrollView.backgroundColor = [UIColor whiteColor];
    if ([self.url isEqualToString:WEBURL3   ]) {
        self.view.backgroundColor = [UIColor whiteColor];
        stateBatHeight   = 0;
    }
    else
    {
        self.view.backgroundColor = [UIColor colorWithHexString:@"#2fb0f4"];
    }
    if (KIsiPhoneX) {
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 44, self.view.bounds.size.width, kScreenHeight-83-44)];
//        _webViewProgressView = [[NJKWebViewProgressView alloc] initWithFrame:CGRectMake(0, 44, [UIScreen mainScreen].bounds.size.width, 2)];
    }
    else
    {
//        _webViewProgressView = [[NJKWebViewProgressView alloc] initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 2)];
         _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, stateBatHeight, self.view.bounds.size.width, self.view.bounds.size.height-49-stateBatHeight)];
    }
   
    _webView.delegate = self;
    self.automaticallyAdjustsScrollViewInsets = NO;
   
    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.url]]];
    _webView.scalesPageToFit = YES;
    [ self.webView loadRequest:req];
    [self.view addSubview:self.webView];
    
    _webViewProgress = [[NJKWebViewProgress alloc] init];
    _webView.delegate = _webViewProgress;
    _webViewProgress.webViewProxyDelegate = self;
    _webViewProgress.progressDelegate = self;
    
    
    _webViewProgressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
//    [self.view addSubview:_webViewProgressView];
    [_webViewProgressView setProgress:0 animated:YES];
    
    _webView.scrollView.bounces = NO;
    [self  internetCheck];
//    NSURLRequest *req = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",self.url]]];
//    _webView.scalesPageToFit = YES;
//    [ self.webView loadRequest:req];
    [_webView stringByEvaluatingJavaScriptFromString:@"window.alert=null;"];
    if (@available(iOS 11.0, *)) {
        _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }

}

-(void)internetCheck
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [ manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
            {
                //未知网络
                NSLog(@"未知网络");
                if (!loadSuccess) {
                    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
                }
            }
                break;
            case AFNetworkReachabilityStatusNotReachable:
            {
                //无法联网
                NSLog(@"无法联网");
                
            }
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                //手机自带网络
                NSLog(@"当前使用的是2g/3g/4g网络");
                if (!loadSuccess) {
                    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
                }
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                //WIFI
                NSLog(@"当前在WIFI网络下");
                if (!loadSuccess) {
                    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
                }
            }
                
        }
    }];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = YES;
     self.tabBarController.tabBar.hidden = NO;
    
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
//    if (!tempView ) {
//        tempView = [[UIView alloc]init];
//    }
//    if (!KIsiPhoneX) {
//        [[UIApplication sharedApplication].keyWindow addSubview:tempView];
//        tempView.backgroundColor = [UIColor whiteColor    ];
//        [tempView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.right.equalTo(tempView.superview);
//            make.bottom.equalTo(tempView.superview).offset(-49);
//            make.height.mas_equalTo(20);
//        }];
//    }
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//    [tempView removeFromSuperview];
    loadSuccess = YES;
    NSArray *nCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    NSHTTPCookie *cookie;
    for (id c in nCookies)
    {
        if ([c isKindOfClass:[NSHTTPCookie class]])
        {
            cookie=(NSHTTPCookie *)c;
            if ([cookie.name isEqualToString:@"PHPSESSID"]) {
                NSNumber *sessionOnly = [NSNumber numberWithBool:cookie.sessionOnly];
                NSNumber *isSecure = [NSNumber numberWithBool:cookie.isSecure];
                NSArray *cookies = [NSArray arrayWithObjects:cookie.name, cookie.value, sessionOnly, cookie.domain, cookie.path, isSecure, nil];
                [[NSUserDefaults standardUserDefaults] setObject:cookies forKey:@"cookie"];
                break;
            }
        }
    }
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"--------------%@",error);
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    
    NSLog(@"%@",request.URL);
//    NSString *currentURL= webView.request.URL.absoluteString;
    NSString *scheme = request.URL.scheme;
    if ([scheme isEqualToString:@"driver"]) {
        NSString *host =  request.URL.host;
        if ([host isEqualToString:@"goToOpenScan"]) {
//             [[webMethod sharedInstance] FaceAuth:self];
            [[webMethod  sharedInstance] openScane:self];
            return NO;
        }
        else if ([host isEqualToString:@"goToFaceAuth"])
        {
            [[webMethod sharedInstance] FaceAuth:self];
            return NO;
        }
        else if ([host isEqualToString:@"goToPlayVideo"])
        {
            [[webMethod sharedInstance] PlayVideo:request.URL.lastPathComponent];
             return NO;
        }
        else if ([host isEqualToString:@"goToShareWx"])
        {
            NSString *str = request.URL.path;
            
            NSArray *array = [str componentsSeparatedByString:@"https://"];
            if (array.count==2) {
                NSString *title = [array[0] stringByReplacingOccurrencesOfString:@"/" withString:@""];
                NSString *url = [NSString stringWithFormat:@"https://%@",array[1]];
                NSDictionary *dic =@{@"title":title,@"url":url};
                [[webMethod sharedInstance] shareAction:dic WithType:WX];
            }
            
        }
        else if ([host isEqualToString:@"goToShareWxPy"])
        {
            NSString *str = request.URL.path;
            
            NSArray *array = [str componentsSeparatedByString:@"https://"];
            if (array.count==2) {
                NSString *title = [array[0] stringByReplacingOccurrencesOfString:@"/" withString:@""];
                NSString *url = [NSString stringWithFormat:@"https://%@",array[1]];
                NSDictionary *dic =@{@"title":title,@"url":url};
                [[webMethod sharedInstance] shareAction:dic WithType:WXPY];
            }
            
        }
        else if ([host isEqualToString:@"goToShareQQ"])
        {
            NSString *str = request.URL.path;
            
            NSArray *array = [str componentsSeparatedByString:@"https://"];
            if (array.count==2) {
                NSString *title = [array[0] stringByReplacingOccurrencesOfString:@"/" withString:@""];
                NSString *url = [NSString stringWithFormat:@"https://%@",array[1]];
                NSDictionary *dic =@{@"title":title,@"url":url};
                [[webMethod sharedInstance] shareAction:dic WithType:QQ];
            }
            
        }
        else
        {
            
        }
        return NO;
    }
    else if ([scheme isEqualToString:@"target"])
    {
        NSString * url = [request.URL.absoluteString stringByReplacingOccurrencesOfString:@"target" withString:@"https"];
        detailViewController *dVC = [[detailViewController alloc]init];
        dVC.url = url;
        dVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:dVC animated:YES];
//        dVC.hidesBottomBarWhenPushed=NO;
        return NO;
    }
//    NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
//    self.title = theTitle   ;
    else
    return YES;
}
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [_webViewProgressView setProgress:progress animated:YES];
//    self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}


@end

